package com.stylefeng.guns.rest.modular.applications.service;

import com.stylefeng.guns.rest.common.persistence.dao.*;
import com.stylefeng.guns.rest.common.persistence.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 电影应用推荐列 服务层实现
 *
 * @author afei
 * @date 2018-09-28
 */
@Service
public class MovieServiceImpl implements IMovieService {
    private final static Integer FIVEDAYS = 1001;
    private final static Integer ONEEMOTH = 1002;
    private final static Integer THREEMOTH = 1003;
    private final static Integer YONGJIU = 1004;
    private final static Integer VIPSTATUS = 1;

    @Autowired
    private LiveMoveMapper liveMoveMapper;

    @Autowired
    private LiveBannerMapper liveBannerMapper;

    @Autowired
    private LiveTypeMapper liveTypeMapper;

    @Autowired
    private LiveAccountMapper liveAccountMapper;

    @Autowired
    private LiveSeriesMapper liveSeriesMapper;

    @Autowired
    private MovieShareMapper movieShareMapper;

    @Autowired
    private AppVersionMapper appVersionMapper;

    @Autowired
    private MovieSeriesRecordMapper movieSeriesRecordMapper;

    @Autowired
    private MoviePayRecordsMapper moviePayRecordsMapper;

    @Autowired
    private MoviePayApplyRecordMapper moviePayApplyRecordMapper;

    @Autowired
    private MovieVipMapper movieVipMapper;


    @Override
    public List<LiveMoviesBO> liveMovesByParams(LiveMovieVo liveMove) {
        List<LiveMove> liveMoves = liveMoveMapper.liveMovesByRandow(liveMove);
       // List<LiveMove> liveMoves = randomTopic(movies, liveMove.getCount());
        Map<Integer, List<LiveMove>> liveMovesMap = liveMoves.stream()
                .collect(Collectors.groupingBy(LiveMove::getTypeNum));
        Set<Map.Entry<Integer, List<LiveMove>>> entryseSet = liveMovesMap.entrySet();
        List<LiveMoviesBO> liveMoviesBOs = new ArrayList<>();
        for (Map.Entry<Integer, List<LiveMove>> entry : entryseSet) {
            LiveMoviesBO bo = new LiveMoviesBO();
            bo.setTypeNum(entry.getKey());
            bo.setLiveMovies(entry.getValue().subList(0, 6));
            liveMoviesBOs.add(bo);
        }
        return liveMoviesBOs;
    }

    @Override
    public List<LiveType> liveTypes() {

        return liveTypeMapper.liveTypes();
    }

    @Override
    public List<LiveMove> homeChangeMovies(LiveMovieVo liveMove) {
        List<LiveMove> liveMoves = liveMoveMapper.liveMovesByParams(liveMove);
        List<LiveMove> movies = randomTopic(liveMoves, liveMove.getCount());
        return movies;
    }

    /**
     * 方法名称: moviesPage 方法描述: 随机获取6条数据 创建人： afei 创建时间 2018年9月22日 下午3:10:40
     */
    private static List<LiveMove> randomTopic(List<LiveMove> list, Integer count) {
        // 创建一个长度为count(count<=list)的数组,用于存随机数
        int[] a = new int[count];
        // 利于此数组产生随机数
        int[] b = new int[list.size()];
        int size = list.size();
        // 取样填充至数组a满
        for (int i = 0; i < count; i++) {
            int num = (int) (Math.random() * size); // [0,size)
            int where = -1;
            for (int j = 0; j < b.length; j++) {
                if (b[j] != -1) {
                    where++;
                    if (where == num) {
                        b[j] = -1;
                        a[i] = j;
                    }
                }
            }
            size = size - 1;
        }
        // a填满后 将数据加载到rslist
        List<LiveMove> rslist = new ArrayList<LiveMove>();
        for (int i = 0; i < count; i++) {
            LiveMove df = (LiveMove) list.get(a[i]);
            rslist.add(df);
        }
        return rslist;
    }

    @Override
    public void updateWatchCount(Integer movieId) {
        //查询电影，然后观看次数+1，在更新
        LiveMove liveMove = liveMoveMapper.selectByPrimaryKey(movieId);
        Integer watchTimes = liveMove.getWatchCount() + 1;
        liveMove.setWatchCount(watchTimes);
        liveMoveMapper.updateByPrimaryKeySelective(liveMove);
    }

    @Override
    public MovieShare selectByParams(MovieShare record) {
        return movieShareMapper.selectByParams(record);
    }

    @Override
    public int insertSelective(MoviePayApplyRecord record) {
        return moviePayApplyRecordMapper.insertSelective(record);
    }

    @Override
    public MoviePayApplyRecord selectByPrimaryKey(Integer id) {
        return moviePayApplyRecordMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(MoviePayApplyRecord record) {
        return moviePayApplyRecordMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public List<MoviePayApplyRecord> payApplyRecord(String accountId) {
        return moviePayApplyRecordMapper.payApplyRecord(accountId);
    }

    @Override
    public MovieVip selectByParams(Integer vipType) {

        return movieVipMapper.selectByParams(vipType);
    }

    @Override
    public void updateVipStatus(MoviePayRecords moviePayRecords) {
        //根据透参数查询交易记录
        MoviePayApplyRecord moviePayApplyRecord = moviePayApplyRecordMapper.selectPayApplyRecord(moviePayRecords.getOrderid());

        //更改支付申请的记录的状态
        moviePayApplyRecordMapper.updatePayStatus(moviePayRecords.getOrderid());
        //根据账号更新会员表里面的vip状态和到期时间
        LiveAccount liveAccount = liveAccountMapper.selectByAccount(moviePayApplyRecord.getAccountId());
        Date now = new Date();
        //1是会员
        Integer vipType = moviePayApplyRecord.getVipType();
        //Integer isVip = liveAccount.getIsVip();
        Date vipTime = liveAccount.getVipTime();
        if (vipTime == null) {
            //首次开通从当前时间开始
            liveAccount.setVipTime(resetVipTime(now, vipType));
        } else {
            if (now.getTime() > vipTime.getTime()) {
                liveAccount.setVipTime(resetVipTime(now, vipType));
            } else {
                //已是vip，续费
                liveAccount.setVipTime(resetVipTime(vipTime, vipType));
            }
        }
        liveAccount.setIsVip(VIPSTATUS);
        liveAccountMapper.updateByPrimaryKeySelective(liveAccount);

    }

    @Override
    public AppVersion selectByType(String type) {
        return appVersionMapper.selectByType(type);
    }

    @Override
    public void updateVipTime(String account, Integer vipType) {
        //开通会员后更新状态及其会员到期时间
        //获取用户信息
        LiveAccount liveAccount = liveAccountMapper.selectByAccount(account);
        Date now = new Date();
        //1是会员
        Integer isVip = liveAccount.getIsVip();
        Date vipTime = liveAccount.getVipTime();
        if (vipTime == null) {
            //首次开通从当前时间开始
            liveAccount.setVipTime(resetVipTime(now, vipType));
        } else {
            if (System.currentTimeMillis() > vipTime.getTime()) {
                liveAccount.setVipTime(resetVipTime(now, vipType));
            } else {
                //已是vip，续费
                liveAccount.setVipTime(resetVipTime(vipTime, vipType));
            }
        }
        liveAccount.setIsVip(VIPSTATUS);
        liveAccountMapper.updateByPrimaryKeySelective(liveAccount);

    }

    @Override
    public List<MovieSeriesRecord> selectByParams(MovieSeriesRecord record) {

        return movieSeriesRecordMapper.selectByParams(record);
    }

    @Override
    public void insertSelective(MoviePayRecords record) {
        moviePayRecordsMapper.insertSelective(record);
    }


    @Override
    public List<LiveMove> moviesPage(LiveMovieVo liveMove) {

        return liveMoveMapper.liveMovesByParams(liveMove);
    }


    @Override
    public List<LiveBanner> liveBanners(LiveBanner record) {
        return liveBannerMapper.queryByParams(record);
    }

    @Override
    public boolean isExist(String token) {

        return liveAccountMapper.isExist(token);
    }

    @Override
    public LiveAccountBO queryByToken(String token) {
        //根据token登录，更新vip状态
        LiveAccountBO liveAccount = liveAccountMapper.queryByToken(token);
        LiveAccount account = new LiveAccount();
        if (liveAccount != null) {
            Date vipTime = liveAccount.getVipTime();
            if (vipTime != null) {
                if (System.currentTimeMillis() > vipTime.getTime()) {
                    account.setId(liveAccount.getId());
                    account.setIsVip(0);
                    //更新当前用户会员状态
                    liveAccountMapper.updateByPrimaryKeySelective(account);
                }
            }
        }
        LiveAccountBO liveAccount1 = liveAccountMapper.queryByToken(token);
        return liveAccount1;
    }

    @Override
    public boolean isVip(String token) {

        LiveAccountBO liveAccount = liveAccountMapper.queryByToken(token);
        if (liveAccount != null) {
            Date vipTime = liveAccount.getVipTime();
            if (System.currentTimeMillis() < vipTime.getTime()) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    @Override
    public List<LiveSeries> selectLiveSeries() {

        return liveSeriesMapper.selectLiveSeries();
    }

    //根据开通会员类型返回到期时间
    public static Date resetVipTime(Date vipTime, Integer vipTpye) {

        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(vipTime);
        if (vipTpye.equals(FIVEDAYS)) {
            rightNow.add(Calendar.DATE, 4);
        } else if (vipTpye.equals(ONEEMOTH)) {
            rightNow.add(Calendar.MONTH, 1);
        } else if (vipTpye.equals(THREEMOTH)) {
            rightNow.add(Calendar.MONTH, 3);
        } else if (vipTpye.equals(YONGJIU)) {
            rightNow.add(Calendar.YEAR, 100);
        }
        return rightNow.getTime();
    }

}
